package cn.itedus.lottery.domain.activity.service.deploy.impl;

import cn.itedus.lottery.domain.activity.model.aggregate.ActivityConfigRich;
import cn.itedus.lottery.domain.activity.model.req.ActivityConfigReq;
import cn.itedus.lottery.domain.activity.model.vo.ActivityVO;
import cn.itedus.lottery.domain.activity.repository.IActivityRepository;
import cn.itedus.lottery.domain.activity.service.deploy.IActivityDeploy;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 部署活动配置服务
 */
@Service
public class ActivityDeployImpl implements IActivityDeploy {

    private Logger logger = LoggerFactory.getLogger(ActivityDeployImpl.class);


    @Resource
    private IActivityRepository activityRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createActivity(ActivityConfigReq activityConfigReq) {
        logger.info("创建活动配置开始：activityId:{}", activityConfigReq.getActivityId());
        ActivityConfigRich activityConfigRich = activityConfigReq.getActivityConfigRich();
        try {

            activityRepository.addActivity(activityConfigRich.getActivity());
            activityRepository.addAward(activityConfigRich.getAwardList());
            activityRepository.addStrategy(activityConfigRich.getStrategy());
            activityRepository.addStrategyDetailList(activityConfigRich.getStrategy().getStrategyDetailList());
            logger.info("创建活动配置完成，activityId: {}", activityConfigReq.getActivityId());

        } catch (DuplicateKeyException e) {
            logger.error("创建活动配置失败，唯一索引冲突 activityId:{} reqJson:{}", activityConfigReq.getActivityId(), JSON.toJSONString(activityConfigReq));
            throw e;
        }

    }

    @Override
    public void updateActivity(ActivityConfigReq activityConfigReq) {
        // TODO: 非核心功能后续补充
    }

    @Override
    public List<ActivityVO> scanToDoActivityList(Long id) {
        return activityRepository.scanToDoActivityList(id);
    }
}
